/***
 * todo:
 * 1. 自定义角色时，如何判定某一新定义角色为运营角色？
 * 2. 插入数据是接口层面增加创建人
 *
 */
$(function () {
    var query = {}, fields = 'id|name|code|unit|qualitySpec|operator|isDanger|isDrugs',
        $search = $('.search'), $searchBar = $('.search-btn');
    var operate = {}, operator_list = [];
    var config = {
        coloum_num: 8, //列数目
        query: '/saleperson/mySales?',//分页查询URL,
        update: '/goods/update',
        'delete': '/goods/delete',
        user: '/user/operator' //运营角色用户
    };
    var searchObj = parseSearch();
    $('.name').html(decodeURI(searchObj.name));

    function search(obj,isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        query = query_;query.timestamp = Date.now(); 
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        arg.push('userId='+searchObj.id);
        $.get(config.query + arg.join('&'), function (res) {
            $searchBar.button('reset');
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            if (_.isEmpty(query)) {
                $('.su-pager').pagination({
                    itemsCount: page.total,
                    pageSize: page.size,
                    styleClass: ['pagination-large'],
                    showCtrl: true,
                    displayPage: 6,
                    onSelect: function (num) {
                        search({page: num});
                        return false;
                    }
                });
                if (!$('.size-select').length) {
                    $('.su-pager').prepend(generatePageSize());
                    $('.size-select').change(function (item) {
                        var size = $(item.target).val();
                        search({size: size, page: 0})
                    })
                }

            }

        });
    }

    function render(list) {
        // $('.table-responsive .table tbody')

        $('.table-responsive .table tbody').html('');
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                // re
                $('.table-responsive .table tbody')
                    .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                <td>' + (item.name||'') + '</td> \
                <td>' + item.userName + '</td> \
                <td>' + item.phone + '</td> \
                </tr>')
            });
        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }

    search({},true);

    // 表单提交
    var $submit = $('#submit');
    $submit.on('click', function () {
        var $btn = $(this).button('loading');
    });

    $("#user-form").validate({
        submitHandler: function (form_) {
            var form = {};
            fields.split('|').map(function (item) {
                if (form_[item].type == 'checkbox') {
                    form[item] = $(form_[item]).is(':checked') ? '1' : '0';
                } else {
                    form[item] = form_[item].value
                }
                form['operatorId'] = Object.keys(operate).toString();
                form['operator'] = Object.keys(operate).map(function (item, index) {
                    return operate[item]
                }).toString();

            });
            var url = config.create;
            if (form.id) { // is update?
                url = config.update;
            } else {
                delete form.id;
            }
            $.post(url, form, function (xhr, data) {
                $submit.button('reset');
            });
            return false;
        }
    });
    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    })
});